package com.ionehe.group.common.uaa.ex.domain.service.impl;

import com.google.common.base.Throwables;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.dto.FunctionDTO;
import com.ionehe.group.common.uaa.ex.dto.UserDetailDTO;
import com.ionehe.group.common.uaa.ex.enums.ErrorMessages;
import com.ionehe.group.common.uaa.ex.domain.service.UserCacheReadService;
import com.ionehe.group.common.uaa.ex.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Copyright (c) 2020 ionehe.com
 * Date: 2020/12/1
 * Time: 11:29 上午
 *
 * @author 2020年 <a href="mailto:a@ionehe.com">秀</a>
 */
@Service
@Slf4j
public class UserCacheReadServiceImpl implements UserCacheReadService {
    @Autowired
    private RedisUtils redisUtils;
    @Value("${redis.database:base}")
    private String redisDatabase;
    @Value("${redis.expire.common:86400}")
    private Long redisExpire;
    @Value("${redis.key.user:uaa:user}")
    private String redisKeyUser;
    @Value("${redis.key.resourceList:uaa:resourceList}")
    private String redisKeyResourceList;

    @Override
    public Response<UserDetailDTO> getUser(String username) {
        log.info("UserCacheReadService[]getUser[]start! username:{}", username);
        try {
            String key = redisDatabase + ":" + redisKeyUser + ":" + username;
            return Response.yes((UserDetailDTO) redisUtils.get(0, key));
        } catch (Exception e) {
            log.error("UserCacheReadService[]getUser[]error! cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no(ErrorMessages.CACHE_DATA_FAIL.toString());
        }
    }

    @Override
    public Response<List<FunctionDTO>> getResourceList(String account) {
        log.info("UserCacheReadService[]getResourceList[]start! account:{}", account);
        try {
            String key = redisDatabase + ":" + redisKeyResourceList + ":" + account;
            return Response.yes((List<FunctionDTO>) redisUtils.get(0, key));
        } catch (Exception e) {
            log.error("AdminCacheReadService[]getResourceList[]error! cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no(ErrorMessages.CACHE_DATA_FAIL.toString());
        }
    }
}
